package com.tempjob.common.context;

import com.tempjob.common.businesss.mongo.entity.SysPermission;
import com.tempjob.common.businesss.mongo.entity.SysAdmin;
import com.tempjob.common.utils.CachedBeanCopier;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import org.apache.commons.lang3.StringUtils;

import java.io.Serializable;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author hui
 * @Date 2021/12/14 下午5:54
 **/
@Data
@ApiModel
public class AdminContext implements Serializable {

    @ApiModelProperty(value = "id")
    private String id;

    @ApiModelProperty(value = "手机号")
    private String phone;

    @ApiModelProperty(value = "用户昵称")
    private String nickname;

    private String username;

    private String realName;

    private String email;

    private Integer status;

    private Integer sex;

    @ApiModelProperty(value = "用户角色")
    private List<String> roles;

    @ApiModelProperty(value = "权限标识")
    private Set<String> permissions;

    @ApiModelProperty(value = "是否管理员", hidden = true)
    private Boolean superAdmin;

    public String getRealName() {
        if (StringUtils.isNoneBlank(realName)) {
            return realName;
        }
        return username;
    }

    public AdminContext() {

    }

    public static AdminContext create(SysAdmin user, List<String> roles, List<SysPermission> permissions) {
        AdminContext userinfo = new AdminContext();
        CachedBeanCopier.copyObject(user, userinfo);
        userinfo.setId(user.getId());
        userinfo.setRoles(roles);
        Set<String> permission = permissions.stream().filter(i -> !StringUtils.isEmpty(i.getPerms())).map(SysPermission::getPerms).collect(Collectors.toSet());
        Set<String> permis = new HashSet<>();
        permission.forEach(i -> {
            List<String> p = Arrays.asList(i.split(","));
            p.forEach(j -> {
                permis.add(j);
            });
        });
        userinfo.setPermissions(permis);
        return userinfo;
    }

}
